package processes;

import java.util.LinkedList;
import main.Lists;
import resources.ResPrimitives;
import resources.Resource;

/**
 *
 * @author Ramunas
 */
public class StartStop extends Process{
    
    public StartStop(){
        this.setName("StartStop");
        this.setId(ProcPrimitives.getUniqueId());
        this.setProgress("0");
        this.setState("Pasiruoses");
        ProcPrimitives.addReady(this);
    }
    
    @Override
    public void go(){
        switch(this.getProgress().toCharArray()[0]){
            case '0': step1();
                    break;
            case '1': step2();
                    break;
            case '2': step3();
                    break;
            case '3': step4();
                    break;
            case '4': step5();
                    break;
        }
    }
    
    public final void step1(){
        //sukuriami resursai  
        this.setProgress("1");
        String[] res = {"Pabaiga","Vartotojo atmintine","Eilute atmintyje"
               ,"Isorine atmintis","Supervizorine atmintis","Kanalu irenginys"};
        
        for(int i = 0; i < res.length; i++){
            ResPrimitives.createResource(res[i], this);
        }
        ProcPrimitives.addReady(this);
        //ProcPrimitives.processPlanner();
    }
    
    public final void step2(){
        //sukuriami procesai
        ProcPrimitives.createProcess(new Interrupt(), this);
        ProcPrimitives.createProcess(new Output(), this);
        ProcPrimitives.createProcess(new Main(), this);
        ProcPrimitives.createProcess(new Loader(), this);
        ProcPrimitives.createProcess(new Swap(), this);
        ProcPrimitives.createProcess(new Distribute(), this);
        ProcPrimitives.createProcess(new Read(), this);
        ProcPrimitives.createProcess(new Branch(), this);
        this.setProgress("2");
        ProcPrimitives.addReady(this);
        //ProcPrimitives.processPlanner();
    }
    
    public final void step3(){
        //blokavimasis, laukiama "pabaiga" resurso
        this.setProgress("3");
        ResPrimitives.requestResource(ResPrimitives.findResource("Pabaiga"), this);
        //ProcPrimitives.processPlanner();
        //Lists.getResources().get("Pabaiga");
        //ResPrimitives.requestResource("Pabaiga", this);
    }
    
    public final void step4(){
        //naikinami procesai
        for(Integer child : this.getChildren()){
            ProcPrimitives.destroyProcess(Lists.getProcessById(child));  
        }
        this.setProgress("4");
        ProcPrimitives.addReady(this);
    }
    
    public final void step5(){
        //naikinam,i resursai
        LinkedList<Resource> resList = this.getCreatedResources();
        int size = resList.size();
        Resource res;
        for(int i = 0; i<size; i++){
            ResPrimitives.destroyResource(resList.removeFirst());
        }           
        this.setProgress("5");
    }      
}